<template>
  <div id="amap-container" class=" rounded shadow border border-gray-300"/>
</template>

<script setup>
import {onMounted, ref, watch} from 'vue'
import AMapLoader from '@amap/amap-jsapi-loader'

const props = defineProps({
  path: {
    type: Array,
    default: () => []
  }
})

const map = ref(null)
const polyline = ref(null)
const startMarker = ref(null)
const endMarker = ref(null)

const startPos = ref(props.path[0])
const endPos = ref(props.path[props.path.length - 1])

watch(() => props.path, (newPath) => {
  startPos.value = newPath[0]
  endPos.value = newPath[newPath.length - 1]

  if (!startPos.value || startPos.value.some(v => typeof v !== 'number' || isNaN(v))) {
    console.warn('起点坐标无效:', startPos.value)
  }

  if (!endPos.value || endPos.value.some(v => typeof v !== 'number' || isNaN(v))) {
    console.warn('终点坐标无效:', endPos.value)
  }

  // ✅ 更新地图轨迹与标记
  if (polyline.value) {
    polyline.value.setPath(newPath)
  }

  if (startMarker.value) {
    startMarker.value.setPosition(startPos.value)
  }

  if (endMarker.value) {
    endMarker.value.setPosition(endPos.value)
  }
}, {immediate: true}) // 初始也执行一次

const initMap = () => {
  AMapLoader.load({
    key: 'e07201732397417d88f1fa40fe9ea4ac',
    version: '2.0',
    plugins: ['AMap.Marker', 'AMap.Polyline']
  }).then((AMap) => {
    map.value = new AMap.Map('amap-container', {
      viewMode: '2D',
      zoom: 14,
      center: startPos.value || [104.06, 30.67],
    })

    polyline.value = new AMap.Polyline({
      path: props.path,
      strokeColor: '#FF4C4C',
      strokeWeight: 8,
      isOutline: true,
      outlineColor: '#FFFFFF',
      lineJoin: 'round',
      lineCap: 'round',
      showDir: true,
      zIndex: 50,
      map: map.value
    })

    startMarker.value = new AMap.Marker({
      position: startPos.value,
      content: "<div class='amap-marker-start'>🚩 设备部署点</div>",
      offset: new AMap.Pixel(-12, -24),
      map: map.value
    })

    endMarker.value = new AMap.Marker({
      position: endPos.value,
      content: "<div class='amap-marker-end'>🚩 设备所在点</div>",
      offset: new AMap.Pixel(-12, -24),
      map: map.value
    })
  }).catch(e => {
    console.error('地图加载失败：', e)
  })
}

onMounted(() => {
  initMap()
})

</script>

<style>
#amap-container {
  width: 100%;
  height: 100%;
  min-height: 630px;
}

.amap-marker-end {
  color: #c23a3a;
  font-weight: bold;
  white-space: nowrap;
  background: white;
  padding: 2px 6px;
  border-radius: 4px;
  border: 1px solid #c23a3a;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

.amap-marker-start {
  color: #67c23a;
  font-weight: bold;
  white-space: nowrap;
  background: white;
  padding: 2px 6px;
  border-radius: 4px;
  border: 1px solid #67c23a;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}
</style>
  